package com.hxm.demo.test1;

/**
 * description: add a description
 *
 * @author huangxiaoming
 * @version 1.0.0
 * @date 2022/10/25 09:03:53
 */
public class TestReverseWords {

    /**
     * 557. 反转字符串中的单词 III
     *
     * @param args
     */
    public static void main(String[] args) {
        String s = "Let's take LeetCode contest";
        System.out.println(reverseWords(s));
    }

    /**
     * 给定一个字符串 s ，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
     *
     * @param s
     * @return
     */
    public static String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int i = 0, j = -1;
        for (int m = 0; m < chars.length; m++) {
            if (chars[m] == ' ') {
                swap(chars, i, j);
                i = m+1;
            }
            j++;
        }
        if (j>i){
            swap(chars, i, j);
        }
        return new String(chars);
    }

    public static void swap(char[] chars, int start, int end) {
        while (start < end) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            start++;
            end--;
        }
    }
}
